package com.itheima.web;

import com.itheima.common.R;
import com.itheima.pojo.Aliyuncs;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.OutputStream;
import java.util.UUID;

/*
* 文件的上传和下载*/
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonConterllor {
    @Value("${reggie.path}")
    private String basePath;

    @Autowired
    private AliOSSUtils aliOSSUtils;
    /*
    * 文件上传*/
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //获取原始文件的名称
        String originalFilename = file.getOriginalFilename();//fdssdf.jpg
        //使用uuid生成文件名防止被覆盖
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+ suffix;
        //创建文件目录
        File dir = new File(basePath);
        if (dir.exists()){
            //如果没有目录就生成
            dir.mkdirs();
        }

        //将上传文件存入指定目录
        /*try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        aliOSSUtils.uploadFile(fileName, file.getInputStream());
        return R.success(fileName);
    }

    /*
    * 文件下载*/
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {

        /*try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));//绝对路径
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //IOUtils.copy(new FileInputStream(new File(basePath+name)),response.getOutputStream());
        aliOSSUtils.downLoadFile(name,response.getOutputStream());


    }


}
